// 添加层级弹窗
import React, { useEffect, useState }  from 'react';
import { Form, Input, message, Modal } from 'antd';
import { saveOrUpdateFolder } from 'src/services/AnalyseManage';

interface Iprops {
	modalVisible: boolean;
	modelId: string;
	folderId: string;
	type: string;
  nodeData: any;
	onSubmit: Function;
	closeModal: Function;
}

// eslint-disable-next-line react/display-name
const ModalAddTier = ( props: Iprops ) => {
	const [ loading, setLoading ] = useState( false );

	const [ form ] = Form.useForm();

	const handleCancle = () => {
		props.closeModal( false );
		form.resetFields();
	};	
	
	const handleOk = () => {
		form.validateFields().then( value => {
			let title = value.title.trim();
			let id = props.nodeData ? props.nodeData.id : null;
			let param = {
				modelId: props.modelId,
				name: title,
				parentId: props.folderId,
				type: props.type,
			};
			if ( id ) {
				param['id'] = id;
			}
			setLoading( true );
			saveOrUpdateFolder( param ).then( res => {
				if ( res.data.success ) {
					props.onSubmit( { title, id } );
					handleCancle();
					setLoading( false );
				} else {
					setLoading( false );
				}
			} );
		} ).catch( info => {
			message.warning( '请完善信息' );
		} );
	};

	useEffect( () => {
		if ( !props.modalVisible ) return;
		if ( props.nodeData && props.nodeData.title ) {
			form.setFieldsValue( { title: props.nodeData.title } );
		}
	}, [ props.modalVisible, props.nodeData, form ] );


	return (
		<Modal okText={'确定'} 
			visible={props.modalVisible}
			confirmLoading={loading}
			cancelText={'取消'} 
			onCancel={handleCancle}
			onOk={handleOk}
			title={ '添加层级' }>
			<Form form={form} labelCol={{ span: 4 }}>
				<Form.Item label="层级名称" name="title" rules={ [ { required: true, message: '不能为空！' } ] }>
					<Input autoComplete="off" />
				</Form.Item>
			</Form>
		</Modal>
	);
};

export default ModalAddTier;